//
//  SearchViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/20.
//

import UIKit
import CoreBluetooth
import TCCKit
class SearchViewController: EPViewController {
    @IBOutlet var tips1: UILabel!
    @IBOutlet var tips2: UILabel!
    var array = [CBPeripheral]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    override func initUI() {
        self.title = LS("搜索设备")
        self.view.backgroundColor = .white
        
        weak var weakself = self
        self.tableViewStyle = .plain
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        let header = self.tableView.mj_header as! MJRefreshNormalHeader
        header.setTitle(LS("搜索设备..."), for: .refreshing)
        self.tableView.refreshBlock = { boo in
            weakself?.search()
        }
        self.tableView.mj_header?.beginRefreshing()
        self.tableView.register(DeviceCell.nib(), forCellReuseIdentifier: DeviceCell.ID())
        self.tableView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview().inset(0)
        }
        
    }
    
    func search(){
        self.array.removeAll()
        BLE.scanPeripheralNames = ["CalidoSock"]
        BLE.maxConnected = 2
        BLE.startScan { [weak self] array in
            self?.array = array
            self?.tableView.reloadData()
        }
        self.perform(#selector(stopSearch), with:nil, afterDelay:10)
    }
    
    @objc func stopSearch(){
        self.tableView.mj_header?.endRefreshing()
        self.tips1.isHidden = self.array.count > 0
        self.tips2.isHidden = self.array.count > 0
    }
    
    func connectResult(_ status:BLEStatus){
        switch status{
        case .connectedSucces:
            CCHud.start("连接成功")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5){
                CCHud.stop()
                self.backBtnAction()
            }
        default:
            break
        }
        tableView.reloadData()
    }
    
}

//MARK: - 蓝牙相关通知
extension SearchViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(actionForBLEStatus), BLEStatusUpdateNotifyName)
    }
    @objc func actionForBLEStatus(){
        self.tableView.reloadData()
    }
}

//MARK: - UITableViewDataSource
extension SearchViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DeviceCell.ID()) as! DeviceCell
        let peripheral = self.array[indexPath.row]
        
        ///解析名称
        let mac_array = peripheral.mac.components(separatedBy: ":")
        if mac_array.count > 1{
            let direction = mac_array[0].hasPrefix("7C") ? "L" : "R"
            let lastTwoMac = mac_array[mac_array.count - 2] + mac_array[mac_array.count - 1]
            let name = peripheral.name! + "_" + lastTwoMac + direction
            peripheral.model = SockModel()
            peripheral.model.name = name
        }else{
            peripheral.model.name = peripheral.name ?? ""
        }
        cell.title.text = peripheral.model.name
        cell.statues.text = peripheral.state == .connected ? LS("已连接") : LS("未连接")
        cell.statues.textHexColor = peripheral.state == .connected ? "#00C2B7" : "#FF485C"
        return cell
    }
    
    
}
//MARK: - UITableViewDelegate
extension SearchViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if BLE.connectedPeripherals.count >= BLE.maxConnected{
            self.alert(LS("提示"), LS("您已连接2个设备，需断开后才能连接新设备")) {} _: {}
            return
        }
        let peripheral = self.array[indexPath.row]
        if peripheral.state == .connected{
            CCHud.start(LS("已连接"),stopTime: 1)
            return
        }
        BLE.connect(peripheral){[weak self] status in
            self?.connectResult(status)
        }
        CCHud.start(LS("连接中"))
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

